package com.zf.yichat.utils.yunshangshuju;

import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.utils.common.HttpUtils;
import com.zf.yichat.utils.common.OKHttpUtil;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;

import java.util.Map;

/**
 * @author idea
 * @date Created in 2020/11/12 11:04
 * @description
 */
public class YsClient {

    public static final String CHARSET_UTF8 = "UTF-8";
    private static final String JSON_PARAM_KEY = "param_json";
    private static final String OTHER_PARAM_KEY = "other";
    private String serverUrl;
    private String accessToken;
    private int connectTimeout;
    private int readTimeout;
    private String appKey;
    private String appSecret;

    public YsClient(String serverUrl, String appKey) {
        this.serverUrl = serverUrl;
        this.appKey = appKey;
    }


    public FsResponse execute(YsBaseReqest request, Class respDataClass) throws Exception {
        Map param = request.getSysParams();
        param.put("apkey", appKey);
        String requestUrl = HttpUtils.buildUrl(serverUrl, null, param);
        String resp = OKHttpUtil.httpGet(requestUrl);
        return this.parse(resp, respDataClass);

    }

    private FsResponse parse(String rsp, Class respDataClass) {
        JSONObject jsonObject = (JSONObject) JSONObject.parse(rsp);
        Integer code = jsonObject.getInteger("code");
        if (code != 200) {
            System.out.println(jsonObject.toJSONString());
            return FsResponseGen.failMsg(jsonObject.get("msg").toString());
        } else {
            return FsResponseGen.successData(jsonObject.getObject("data", respDataClass));
        }
    }
}
